package com.onland.dfish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.onland.dfish.entity.Sort;
import com.onland.dfish.mapper.SortMapper;
import com.onland.dfish.service.ISortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("sortService")
public class SortServiceImpl implements ISortService {
    @Autowired
    private SortMapper sortMapper;

    @Override
    public int createSort(Sort s) {
        return sortMapper.insert(s);
    }

    @Override
    public List<Sort> querySort(int level) {
        if (!(1 == level || 2 == level || 0 == level)) {
            throw new IllegalArgumentException("视频分类等级错误【" + level + "】");
        }
        //打包查询条件
        QueryWrapper<Sort> wrapper = new QueryWrapper<>();
        if (0 != level) {
            wrapper.eq("level", level);
        }
        return sortMapper.selectList(wrapper);
    }

    @Override
    public List<Sort> querySubSort(int pId) {
        //打包查询条件
        QueryWrapper<Sort> wrapper = new QueryWrapper<>();
        wrapper.eq("p_id", pId);
        return sortMapper.selectList(wrapper);
    }

    @Override
    public int removeSort(int id) {
        return sortMapper.deleteById(id);
    }

    @Override
    public Sort getSort(int id) {
        return sortMapper.selectById(id);
    }

    @Override
    public int modifySort(Sort s) {
        return sortMapper.updateById(s);
    }

    @Override
    public List<Sort> selectAll() {
        //查询所有一级分类
        List<Sort> supSortList = querySort(1);
        //查询二级分类
        List<Sort> subSortList = querySort(2);
        for (Sort supSort : supSortList) {
            //一级分类ID
            int id = supSort.getId();
            List<Sort> subSorts = new ArrayList<>();
            for (Sort subSort : subSortList) {
                int pId = subSort.getPId();
                if (id == pId) {
                    subSorts.add(subSort);
                }
            }
            //设置二级分类列表
            supSort.setSubSortList(subSorts);
        }
        return supSortList;
    }
}
